// subPages/health/submitOrders/submitOrders.js
const app = getApp();
var util =  require('../../../utils/util.js');
var isBuy = false
Page({

  /**
   * 页面的初始数据
   */
  data: {

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    if(options.list){
      if(options.type && options.type == 1){
        var list = []
        list.push(JSON.parse(options.list))
        var buyNum = 1
        if(options.num){
          buyNum = options.num
        }
        that.setData({
          type: options.type,
          shopList: list,
          buyNum: buyNum,
          total: ((parseFloat(list[0].xsqg_price?list[0].xsqg_price:list[0].price)*Number(buyNum)) + parseFloat(list[0].yunfei?list[0].yunfei: 0)).toFixed(2)
        })
      }else if(options.type && options.type == 2 && options.total){
        var list = JSON.parse(options.list)
        that.getData(list,options.total,options.type)
      }
    }
  },

  //获取地址数据
  getAddressData:function(){
    var that = this
    util.getAjax(app.globalData.apiUrl +'/get_user_address',function(res){
      // console.log(res)
      if(res.data.length!=0){
        that.setData({
          isAddress: true,
          addressList: res.data[0],
        })
      }else{
        that.setData({
          isAddress: false,
          addressList: [],
        })
        util.showModelAll('提示','请添加收货地址',function(){
          wx.navigateTo({
            url: '/subPages/mine/newAddress/newAddress?isOne=' + 1,
          })
        })
      }
    },{type:1,user_id: that.data.userId})
  },

  //获取购物车数据
  getData:function(idList,total,type){
    var that = this
    util.getAjax(app.globalData.apiUrl +'/community_health_shop_product_buycar_out',function(res){
      // console.log(res)
      for(let i in res.data){
        let num = 0
        let price = 0
        for(let j in res.data[i].items){
          price +=  (parseFloat(res.data[i].items[j].price) * Number(res.data[i].items[j].num)) + parseFloat(res.data[i].items[j].product_content.yunfei?res.data[i].items[j].product_content.yunfei:0).toFixed(2)
          num += Number(res.data[i].items[j].num)
        }
        res.data[i].price = price
        res.data[i].num = num
        res.data[i].yunfei = res.data[i].items[0].product_content.yunfei?res.data[i].items[0].product_content.yunfei:0
      }
      that.setData({
        type: type,
        shopList: res.data,
        total: total
      })
    },{id: idList})
  },

  //地址管理
  addressBtn:function(){
    wx.navigateTo({
      url: '/subPages/mine/address/address',
    })
  },

  //新增地址管理
  newAddressBtn:function(){
    wx.navigateTo({
      url: '/subPages/mine/newAddress/newAddress?isOne=' + 1,
    })
  },

  //购买
  buyBtn:function(){
    var that = this
    if(isBuy){
      return
    }
    isBuy = true
    if(that.data.isAddress){
      var addressList = that.data.addressList
      if(addressList){
        var shopList = that.data.shopList
        var allProduct = []
        var allId = []
        if(that.data.type == 1){
          allProduct = [
            {
              shop_id: shopList[0].shop_id,
              price: that.data.total,
              items: [
                {
                  product_id: shopList[0].id,
                  num: that.data.buyNum,
                  price: that.data.total
                }
              ]
            }
          ]
        }else if(that.data.type == 2){
          allProduct = shopList
          for(var i in shopList){
            for(var j in shopList[i].items){
              allId.push(shopList[i].items[j].id)
            }
          }
        }
        util.postAjax(app.globalData.apiUrl +'/community_health_shop_product_pay',function(res){
          console.log(res)
          var orderNum = res.data.pay_order_id
          wx.requestPayment({
            timeStamp: res.data.timeStamp,
            nonceStr: res.data.nonceStr,
            package: res.data.package,
            signType: res.data.signType,
            paySign: res.data.paySign,
            success(pay){
              if(pay.errMsg == 'requestPayment:ok'){
                util.postAjax(app.globalData.apiUrl +'/community_health_shop_product_pay_ok',function(res){
                  console.log(res)
                  if(res.data == 1){
                    wx.navigateTo({
                      url: '/subPages/mine/orderDetails/orderDetails?orderNum=' + orderNum + '&orderclass=1',
                    })
                  }
                  isBuy = false
                },{all_order_num: orderNum})
              }
             },
             fail(payErr){
              console.log(payErr)
              isBuy = false
              //取消支付
              wx.navigateTo({
                url: '/subPages/mine/orderDetails/orderDetails?orderNum=' + orderNum +'&orderclass=1',
              })
             }
          })
        },{
          address: addressList.address,
          sheng: addressList.sheng,
          shi: addressList.shi,
          qu: addressList.qu,
          name: addressList.name,
          phone: addressList.phone,
          user_id: that.data.userId,
          all_product: allProduct,
          all_price: that.data.total,
          all_id: allId
        })
      }else{
        util.showToast('加载失败，请重试','none',1000)
        isBuy = false
      }
    }else{
      isBuy = false
      util.showModelAll('提示','请添加收货地址',function(){
        wx.navigateTo({
          url: '/subPages/mine/newAddress/newAddress?isOne=' + 1,
        })
      })
    }

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this
    if(app.globalData.userId){
      that.setData({
        userId: app.globalData.userId
      })
      that.getAddressData()
    }else{
      app.userIdCallback = userId => {
        if (userId != '') {
          that.setData({
            userId: userId
          });
          that.getAddressData()
        }
      }
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})
